# coding=utf-8

# coding=utf-8

import urllib

import requests

s_url = 'https://music.2333.me/'

_types = ['qq', 'netease', 'kugou', 'kuwo', 'xiami', 'baidu', '1ting', 'migu', 'lizhi', 'qingting', 'ximalaya', 'kg',
          '5singyc', '5singfc']


def __fetch_music(name, _type, page=1):
    payload = {
        "filter": "name",
        "input": name,
        "page": page,
        "type": _type
    }
    if isinstance(name, unicode):
        temp = name.encode('utf-8')
    else:
        temp = name
    headers = {
        'accept': "application/json, text/javascript, */*; q=0.01",
        'origin': "https://music.2333.me",
        'x-requested-with': "XMLHttpRequest",
        'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
        'content-type': "application/x-www-form-urlencoded",
        'referer': "https://music.2333.me/?name={}&type=qq".format(urllib.quote(temp)),
        'accept-encoding': "gzip, deflate, br",
        'accept-language': "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
    }
    response = requests.post(s_url, data=payload, headers=headers)
    data = response.json().get('data')
    return data


def fetch_music(name):
    page = 1
    ll = []
    for t in _types:
        data = __fetch_music(name, t, page)
        if isinstance(data, list) and len(data) > 1:
            ll += data
            break

    data = [__wrap(item) for item in ll]
    return data[:8]


def __wrap(item):
    title = item.get('title')
    author = item.get('author')
    url = item.get('url')
    link = item.get('link')
    pic = item.get('pic')
    s_type = item.get('type')  # 来源
    data = {
        'Title': u'{}-{})'.format(title, author),
        'Description': u'{}-{}({})'.format(title, author, s_type),
        'PicUrl': pic,
        'Url': url
    }
    return data


if __name__ == '__main__':
    print fetch_music(u'如歌张杰')
